<template>
  <a-modal
    v-if="showModal"
    v-model:visible="showModal"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title> {{ modalTitle }} </template>
    <dept-tree
      :checkable="true"
      :checkedKeys="treeCheckedKeys"
      :disabledKeys="treeDisabledKeys"
      @dept-tree-checked-change="deptTreeCheckedChange"
    ></dept-tree>
  </a-modal>
</template>
<script lang='ts'>
import { useI18n } from "vue-i18n";
import { defineComponent, Ref, ref, toRefs, watch } from "vue";
import DeptTree from "./dept-tree.vue";
import { isBlankForArray } from "/@/kit/blank-kit";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "DeptTreeModal",
  props: {
    visible: Boolean,
    checkedKeys: {
      type: Array,
      default: () => [],
    },
    disabledKeys: {
      type: Array,
      default: () => [],
    },
  },
  emits: ["ok", "cancel", "update:visible"],
  components: {
    DeptTree,
  },
  setup(props, { emit }) {
    const { t } = useI18n();
    const { visible, checkedKeys, disabledKeys } = toRefs(props);
    const modalTitle = t("org.dept.selectDepartment");
    //显示弹窗
    const showModal = ref(visible.value);
    //默认选中的部门
    const treeCheckedKeys = ref(checkedKeys.value as Array<string>);
    //默认禁用的部门
    const treeDisabledKeys = ref(disabledKeys.value as Array<string>);
    //监听visible的值 修改显示
    watch(visible, (val) => {
      showModal.value = val;
    });

    //监听选中的值
    watch(checkedKeys, (val) => {
      treeCheckedKeys.value = val as Array<string>;
    });

    //在部门树被选中时 修改已经选中的值
    const deptTreeCheckedChange = (val: any) => {
      treeCheckedKeys.value = val.checked;
    };

    const handleOk = () => {
      //如果为空则提示
      if (isBlankForArray(treeCheckedKeys.value)) {
        message.warning(t("org.dept.notSelectedDeptTips"));
        return false;
      }
      emit("ok", treeCheckedKeys.value);
    };

    const handleCancel = () => {
      emit("update:visible", false);
      emit("cancel");
    };

    return {
      modalTitle,
      showModal,
      handleOk,
      handleCancel,
      treeCheckedKeys,
      treeDisabledKeys,
      deptTreeCheckedChange,
    };
  },
});
</script>
